package com.educhains.module.user.service.impl;

import com.educhains.module.demo.vo.Page;
import com.educhains.module.user.persist.mybatis.UserMapper;
import com.educhains.module.user.service.UserService;
import com.educhains.module.user.vo.User;
import com.educhains.web.util.CipherUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author YuRun
 * @since 2017年8月19日
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper = null;

    public User getUserByEmail(String userEmail) {
        return userMapper.getUserByEmail(userEmail);
    }

    public int addUser(User user) {
        return userMapper.insert(user);
    }

    public int updateUserAuthority(User user) {
        return userMapper.updateUserAuthority(user.getUserEmail(), user.getUserAuthority());
    }

    public List<User> selectUserList() {
        return userMapper.selectUserList();
    }

    public List<User> searchByEmail(String emailFragment){
        emailFragment = "%" + emailFragment+ "%";
        return userMapper.searchByEmail(emailFragment);
    }

    public Page showUserPage(int pageNum) {

        int totalRecord = userMapper.selectUserList().size();
        Page page = new Page(pageNum, totalRecord);
        List list = userMapper.showByPage(page.getStartIndex(), page.getPageSize());
        page.setList(list);
        return page;
    }

    public Page searchByEmailPage(int pageNum, String emailFragment) {
        emailFragment = "%" + emailFragment+ "%";
        int totalRecord = userMapper.searchByEmail(emailFragment).size();
        Page page = new Page(pageNum, totalRecord);
        List list = userMapper.searchByEmailPage(page.getStartIndex(), page.getPageSize(), emailFragment);
        page.setList(list);
        return page;
    }

    public List<User> selectUserListLimit(int userNum, String type) {
        return userMapper.selectUserListLimit(userNum, type);
    }

    public int updateContributionByUserEmail(String userEmail, float contribution) {
        return userMapper.updateContributionByUserEmail(userEmail, contribution);
    }

    public int updateUserPassword(User user) {
        return userMapper.updateUserPassword(user);
    }

    public boolean login(String userEmail, String userPassword, String userSalt) {
        User dbUser = userMapper.getUserByEmail(userEmail);
        if (dbUser == null) {
            return false;
        }
        String inputString = userPassword + userSalt;
        return CipherUtils.validatePassword(dbUser.getUserPwd(), inputString);
    }

    public int updateUserPhoto(User user) {
        return userMapper.updateUserPhoto(user);
    }

    public User selectUserById(String userId) {
        return userMapper.selectUserById(userId);
    }
}
